﻿using System;
using System.Net;
using System.Web;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;

namespace Kindohm.KSynth.UI.Web
{
    public partial class Copy : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Response.Clear();
            this.Response.ContentType = "text/plain";
            string url = this.Request["url"];
            string keywords = this.Request["k"];
            
            WebClient client = new WebClient();
            string data = client.DownloadString(url);

            data = this.Cleanse(data);

            List<int> keywordIndices = this.GetKeywordIndeces(keywords, data);

            string comma = string.Empty;
            StringBuilder output = new StringBuilder();
            for (int i = 0; i < keywordIndices.Count; i++)
            {
                output.AppendFormat("{1}{0}", keywordIndices[i].ToString(), comma);
                if (comma == string.Empty)
                    comma = ",";
            }
            output.Append("%DATA%");
            output.Append(data);
            this.Response.Write(output.ToString());
        }

        string Cleanse(string input)
        {
            System.Text.StringBuilder builder = new System.Text.StringBuilder(input);
            List<string> badStuff = new List<string>() { "<p", "</p>", "<html", "</html>", "<div", "</div>", "<body", "</body>",
            "<img ", "</img>", "src=\"", "class=\"", "<link ", "<meta ", "alt=\"", ".jpg", ".png", ".gif", ".css", ".xml", "<form ",
            "<head", "</head>", "<title>", "</title>", "href", "http://", ".htm", ".html", ".aspx", ".php", "<a ", "<li", "</li>",
            "<ul", "</ul>","<script", "</script>", "onclick=", "<b>", "</b>", "<em>", "</em>", "<strong>", "</strong>",
            "target=\"_blank\"", "target=", "type=\"text/javascript\"", "rel=", "id=", "<span", "</span>", "<!DOCTYPE", ".dtd", "xmlns=\"http://www.w3.org/1999/xhtml\""};

            foreach (string item in badStuff)
                builder.Replace(item, string.Empty);
            return builder.ToString();
        }

        List<int> GetKeywordIndeces(string keywordInput, string data)
        {
            string[] keywords = keywordInput.Split(',');
            List<int> keywordIndices = new List<int>();

            for (int i = 0; i < keywords.Length; i++)
            {
                if (!string.IsNullOrEmpty(keywords[i].Trim()))
                {
                    Regex regex = new Regex(keywords[i].Trim());
                    Match match = regex.Match(data);
                    while (match.Success)
                    {
                        keywordIndices.Add(match.Index);
                        match = match.NextMatch();
                    }
                }
            }
            return keywordIndices;
        
        }
    }
}
